<template>
	<view class="inviteCode">
		<view class="canvas">
			<!-- <view class="share-banner-box"> -->

			<swiper :indicator-dots="true" :autoplay="false" :interval="5000" :duration="150"
				class="tui-banner-swiper tui-skeleton-rect" :circular="true" indicator-color="rgba(255, 255, 255, 0.8)"
				indicator-active-color="#f00" @change="change">
				<swiper-item v-for="(item, index) in imgsArr" :key="index">
					<view class="yui-share-block">
						<!-- <view class="inviteCode-face-imgs"><image :src="codeData.user_headimg" class="tui-avatar"></image></view> -->
						<!-- <view class="inviteCode-nick">{{codeData.nick_name}}</view> -->
						<!-- 	<view class="inviteCode-desc">
							<text class="inviteCode-desc-title">0投资，0风险，0泡沫</text>
							<text class="inviteCode-desc-title-small">正常消费，排队分红，人人有奖</text>
							<text class="inviteCode-desc-title-small">免费注册，先到先排，共同富裕</text>
						</view> -->
					</view>
					<view v-if="index==0 && needLongTapSaveImg[index]==false"> <canvas
							:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok"
							canvas-id="firstCanvas"></canvas></view>
					<view v-else-if="index==1 && needLongTapSaveImg[index]==false"> <canvas
							:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok"
							canvas-id="twoCanvas"></canvas></view>
					<view v-else-if="index==2 && needLongTapSaveImg[index]==false"> <canvas
							:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok"
							canvas-id="threeCanvas"></canvas></view>
					<view v-else-if="index==3 && needLongTapSaveImg[index]==false"> <canvas
							:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok"
							canvas-id="fourCanvas"></canvas></view>
					<view v-else-if="needLongTapSaveImg[index]==false"> <canvas
							:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok"
							canvas-id="fiveCanvas"></canvas></view>
					<view v-show="needLongTapSaveImgs">
						<image :src="tempFilePaths[index]"
							:style="{ width: cansWidth + 'px', height: cansHeight + 'px' }" class="yui-share-blcok">
						</image>
					</view>
				</swiper-item>
			</swiper>
			<!-- </view> -->
		</view>


		<view class="share_footer">
			<view class="share_box">
				<view class="share_box_span" @click="share">
					<image src="/static/images/share/weixin.png" class="share_icon" mode="widthFix"></image>
					<text class="share_box_text">分享微信好友</text>
				</view>
				<view class="share_box_span" @click="share">
					<image src="/static/images/share/pyq.png" class="share_icon" mode="widthFix"></image>
					<text class="share_box_text">朋友圈</text>
				</view>
				<view class="share_box_span" @click="saveCans(1)">
					<image src="/static/images/share/save.png" class="share_icon" mode="widthFix"></image>
					<text class="share_box_text">保存图片</text>
				</view>
			</view>

		</view>

	</view>
</template>

<script>
	var that
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				codeImg: '',
				username: '',
				codeData: '',
				width: '',
				height: '',
				bottom: '',
				shareId: uni.getStorageSync('account'),
				cansWidth: 310, //海报宽度
				cansHeight: 570, //海报高度
				widths: "", //图片列表动态宽度
				imgsrc: "", //保存图片的路径
				userdata: {}, //个人数据
				swiperList: [], //海报数组
				shareText: '邀请好友注册领收益',
				image: '',
				imgsArr: '',
				tempFilePaths: [],
				needLongTapSaveImgs: false,
				indexs: 0,
				needLongTapSaveImg: {
					'0': false,
					'1': false,
					'2': false,
					'3': false,
					'4': false,
				},
				userinfo: '',

			}
		},
		onShow() {
			that = this
			this.tui.haslogin();
			if (this.tui.isLogin()) {
				that.initData();

			}
		},
		onShareAppMessage() {
			this.userinfo = this.tui.getUserInfoData();
			return {
				title: this.shareText ? this.shareText : "山海棠",
				path: '/pages/login/login' ,
				imageUrl: this.image
			}
		},
		

		onLoad(e) {

		},

		methods: {
			initData() {
				let imgs = that.tui.getImgs();
				let token = that.tui.getToken();
				let datas = {
					token: token,
				};

				//#ifdef MP
				let methodsUrl = 'shareWeachtImgsCode';
				//#endif
				// #ifndef MP
				let methodsUrl = 'shareImgsCode';
				// #endif
				let result = that.tui.request('user', 'post', datas, 1000, 1, '', methodsUrl);
				Promise.resolve(result).then((value) => {
					if (value.code == 200) {

						that.codeImg = value.data.qr_code;
						that.imgsArr = value.data.qr_bg;
						that.codeData = value.data;
						that.tui.setImgs(value.data.qr_bg);

						that.imgsArr.forEach((item, index) => {
							that.selseimg(item, index)
						});
						// that.shareImg();
						//#ifdef H5
						setTimeout(() => {
							this.onShare();
						}, 1000)
						//#endif
					} else {
						that.tui.toast(value.message);
					}
				})
				// }
			},
			change(e) {
				this.indexs = e.detail.current;

			},
			shareImg() {
				//数据请求结束
				uni.showLoading({
					title: '加载中'
				});
				uni.hideLoading();
				//数据请求结束
				that.selseimg(that.codeData.qr_bg)
			},
			selseimg(e, index) { //绘制海报
				let names = '';
				let rain = 2;
				switch (index) {
					case 0:
						names = 'firstCanvas';
						break;
					case 1:
						names = 'twoCanvas';
						break;
					case 2:
						names = 'threeCanvas';
						break;
					case 3:
						names = 'fourCanvas';
						break;
					case 4:
						names = 'fiveCanvas';
						break;
					default:
						break;
				}

				uni.showLoading({
					title: '生成海报中'
				});


				const context = uni.createCanvasContext(names)
				//#ifdef MP
				uni.downloadFile({
					url: that.codeImg,
					success: function(res) {
						that.codeImg = res.tempFilePath
					}
				})
				uni.downloadFile({
					url: that.codeData.user_headimg,
					success: function(res) {
						that.codeData.user_headimg = res.tempFilePath
					}
				})
				//#endif

				uni.downloadFile({
					url: e,
					success: function(res) {

						// 图片加圆角
						that.handleBorderRect(context, 0, 0, that.cansWidth, that.cansHeight, 6 * rain);
						context.clip();

						context.drawImage(res.tempFilePath, 0, 0, that.cansWidth, that.cansHeight);

						setTimeout(function() { //定时器，海报方法不能立即执行，等页面渲染完成
							// that.handleBorderRect(context, 27*rain, 94*rain, 75*rain, 75*rain, 6*rain);

							context.drawImage(that.codeImg, 96, 276, 120, 120) //个人信息背景
							context.setFillStyle('#a2a2a2')
							context.setFontSize(12)

							context.setFillStyle('#565555')
							context.setFontSize(13)
							context.fillText(that.codeData.codes, 130, 246)
							context.fill()

							context.arc(44, 452, 24, 0, 2 * Math.PI)
							context.clip()
							// context.drawImage(that.codeData.user_headimg, 17, 427, 52, 52) //头像
							// context.restore()
							// context.draw()



							context.save()
							context.beginPath()
							// context.arc(44, 458, 24, 0, 2 * Math.PI)
							context.clip()


							context.fill()
							let tempRatio = 1.5;

							// #ifdef H5 || APP-PLUS

							tempRatio = 1;
							// #endif

							context.draw(true, () => {

								setTimeout(() => {

									uni.canvasToTempFilePath({
										x: 0,
										y: 0,
										width: that.cansWidth * tempRatio,
										height: that.cansHeight * tempRatio,
										destWidth: that.cansWidth * tempRatio *
											2,
										destHeight: that.cansHeight *
											tempRatio * 2,
										canvasId: names,
										success: (ress) => {

											// 	return;
											//#ifdef H5

											that.needLongTapSaveImg[
												index] = true;
											that.needLongTapSaveImgs =
												true;
											//#endif
											that.tempFilePaths.push(ress
												.tempFilePath)
										}
									})

								})
							})
							uni.hideLoading();
						}, 100);
						uni.hideLoading();
						context.draw(true, function() {
							// uni.canvasToTempFilePath({
							// 	canvasId: 'activityCanvas',
							// 	fileType: 'png',
							// 	// destWidth: that.cansWidth,
							// 	// destHeight: that.cansHeight,
							// 	success: function(ress) {
							// 		// uni.hideLoading();
							// 		successFn && successFn(ress.tempFilePath);
							// 	}
							// })
						});
					}
				})

			},
			/**
			 * 图片圆角设置
			 * @param string x x轴位置
			 * @param string y y轴位置
			 * @param string w 图片宽
			 * @param string y 图片高
			 * @param string r 圆角值
			 */
			handleBorderRect(ctx, x, y, w, h, r) {
				ctx.beginPath();
				// 左上角
				ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI);
				ctx.moveTo(x + r, y);
				ctx.lineTo(x + w - r, y);
				ctx.lineTo(x + w, y + r);
				// 右上角
				ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI);
				ctx.lineTo(x + w, y + h - r);
				ctx.lineTo(x + w - r, y + h);
				// 右下角
				ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
				ctx.lineTo(x + r, y + h);
				ctx.lineTo(x, y + h - r);
				// 左下角
				ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI);
				ctx.lineTo(x, y + r);
				ctx.lineTo(x + r, y);

				ctx.fill();
				ctx.closePath();
			},
			saveCans(e) { //保存海报
			
				let names = '';
				switch (this.indexs) {
					case 0:
						names = 'firstCanvas';
						break;
					case 1:
						names = 'twoCanvas';
						break;
					case 2:
						names = 'threeCanvas';
						break;
					case 3:
						names = 'fourCanvas';
						break;
					case 4:
						names = 'fiveCanvas';
						break;
					default:
						break;
				}
				//#ifdef H5
				this.tui.toast("请长按保存图片");
				return;
				//#endif
				
				//#ifdef APP-PLUS
				uni.showLoading({
					title: '保存海报中'
				});
				// #endif
				let tempRatio = 1.5;
				// #ifdef H5 || APP-PLUS
				tempRatio = 1;
				// #endif
				
				let that = this;
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.cansWidth * tempRatio,
					height: that.cansHeight * tempRatio,
					destWidth: that.cansWidth * tempRatio * 2,
					destHeight: that.cansHeight * tempRatio * 2,
					canvasId: names,
					success: function(res) {
						uni.hideLoading()

						/* 小程序 */
						// #ifdef MP-WEIXIN
				
						uni.getSetting({ //获取用户的当前设置
							success: (ress) => {
								if (ress.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
									that.aveImageToPhotosAlbum(res.tempFilePath);
								} else {
									uni.authorize({ //如果没有授权，向用户发起请求
										scope: 'scope.writePhotosAlbum',
										success: () => {
											that.aveImageToPhotosAlbum(res.tempFilePath);
										},
										fail: () => {
											// 提示
											uni.showToast({
												title: "请打开保存相册权限，再点击保存到手机",
												icon: "none",
												duration: 3000
											});
											setTimeout(() => {
												uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
													success: (
														res2) => {
														// console.log(res2.authSetting)
													}
												});
											}, 3000);
										}
									})
								}
							}
						})
						//#endif
						// #ifndef MP-WEIXIN
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(red) {
								uni.showToast({
									title: '保存相册成功'
								})
								that.imgsrc = res.tempFilePath
								if (e == 2) {

								}
							},
							fail(res) {
								if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
									uni.showModal({
										title: '您需要授权相册权限',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {

													},
													fail(res) {
														console.log(res)
													}
												})
											}
										}
									})
								}
							}
						});
						// #endif

					},
					fail(res) {
						uni.hideLoading()
					}
				}, this)
				
			},
			aveImageToPhotosAlbum(filePath) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
						uni.saveImageToPhotosAlbum({ // 保存图片到系统相册
							filePath: filePath,
							success: function(res2) {
								uni.hideLoading();
								uni.showToast({
									title: '保存成功',
									icon: "none",
									duration: 5000
								})
							},
							fail: function(err) {
								uni.hideLoading();
								// console.log(err.errMsg);
							}
						})
			},
			share() {
				let names = '';
				switch (this.indexs) {
					case 0:
						names = 'firstCanvas';
						break;
					case 1:
						names = 'twoCanvas';
						break;
					case 2:
						names = 'threeCanvas';
						break;
					case 3:
						names = 'fourCanvas';
						break;
					case 4:
						names = 'fiveCanvas';
						break;
					default:
						break;
				}

				//#ifdef H5
				this.tui.toast("请用微信右上角分享");
				return;
				//#endif
				//#ifdef MP-WEIXIN
				this.tui.toast("请用微信右上角分享");
				return;
				//#endif
				let tempRatio = 1.5;

				// #ifdef H5 || APP-PLUS
				tempRatio = 1;
				// #endif

				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.cansWidth * tempRatio,
					height: that.cansHeight * tempRatio,
					destWidth: that.cansWidth * tempRatio * 2,
					destHeight: that.cansHeight * tempRatio * 2,
					canvasId: names,
					success: function(res) {
						// uni.hideLoading()
						uni.shareWithSystem({
							provider: "weixin",
							// scene: "WXSceneSession",
							type: 2,
							imageUrl: res.tempFilePath,
							success: function(res) {
								uni.showToast({
									title: JSON.stringify(err),
									duration: 2000,
									icon: 'none'
								});
							},
							fail: function(err) {

								console.log("fail:" + JSON.stringify(err));
							}
						});
					},
					fail(res) {
						uni.hideLoading()
					}
				}, this)

			},
			shareLine() {
				let tempRatio = 1.5;
				// #ifdef H5 || APP-PLUS
				tempRatio = 1;
				// #endif
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.cansWidth * tempRatio,
					height: that.cansHeight * tempRatio,
					destWidth: that.cansWidth * tempRatio * 2,
					destHeight: that.cansHeight * tempRatio * 2,
					canvasId: 'firstCanvas',
					success: function(res) {
						//#ifdef H5
						that.tui.toast("请用微信右上角分享");
						return;
						return;
						//#endif
						// uni.hideLoading()
						uni.share({
							provider: "weixin",
							scene: "WXSenceTimeline",
							type: 2,
							imageUrl: res.tempFilePath,
							success: function(res) {
								uni.showToast({
									title: JSON.stringify(err),
									duration: 2000,
									icon: 'none'
								});
							},
							fail: function(err) {

								console.log("fail:" + JSON.stringify(err));
							}
						});
					},
					fail(res) {
						uni.hideLoading()
					}
				}, this)
			},

			onShare() {
				//#ifdef APP-PLUS
				plus.share.sendWithSystem({
						content: '商城',
						href: ''
					},
					function() {
						console.log('分享成功');
					},
					function(e) {
						console.log('分享失败：' + JSON.stringify(e));
					}
				);
				//#endif
				// #ifdef H5
				this.userinfo = this.tui.getUserInfoData();
				let urls = this.tui.getUrl() + 'index.html#pages/login/reg/reg?shareid=' + this.userinfo.codes;



				var jweixin = require('jweixin-module')
				let token = this.tui.getToken();
				let obj = {
					token: token,
					url: encodeURIComponent(window.location.href.split('#')[0]),
				}
				// console.log(window.location.href.split('#'))
				let orders = this.tui.request('user', 'post', obj, 1000, 1, '', 'wxShare');
				let that = this;
				Promise.resolve(orders).then((value) => {
					if (value.code == 200) {

						jweixin.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。  
							appId: value.data.appId, // 必填，公众号的唯一标识  
							timestamp: value.data.timestamp, // 必填，生成签名的时间戳  
							nonceStr: value.data.nonceStr, // 必填，生成签名的随机串  
							signature: value.data.signature, // 必填，签名，见附录1  
							surl: value.data.url, //自己添加的，debug为true的时候可以网页打印出对应的URL是否正确  
							jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"],
						});
						jweixin.ready(function() {
							//自定义“分享给朋友”及“分享到QQ”按钮的分享内容（1.4.0）

							let descs = '一起轻松分享，一起轻松创业！';
							jweixin.updateAppMessageShareData({
								title: '领现金红包，人人有礼，直接提现！！',
								desc: descs, // 分享描述
								link: urls,
								imgUrl: that.imgsArr[0],
								success: function(res) {

								},

							});
							//自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）  
							jweixin.updateTimelineShareData({
								title: '领现金红包，人人有礼，直接提现！',
								link: urls,
								imgUrl: that.imgsArr[0],
								success: function() {
									// 用户确认分享后执行的回调函数  
								},
							});

						});
					} else {

						this.showToast(value.message)

					}
				})

				// #endif
			},
		}
	}
</script>

<style lang="scss">
	page {
		background: #f7f7f7;
	}

	.inviteCode-face {
		font-size: 24rpx;
		margin: 40rpx;
	}

	.inviteCode-face-imgs {
		text-align: left;
		margin-top: -80rpx;
	}

	.inviteCode-desc-title {
		font-weight: blod;
		display: block;
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}

	.tui-banner-swiper {
		width: 100%;
		height: 610px;
		// margin:0 auto;
		text-align: center;
		border-radius: 12rpx;
		margin-top: 20rpx;
		overflow: hidden;
		transform: translateY(0);
	}

	.inviteCode-desc-title-small {
		font-size: 26rpx;
		display: block;
		color: #a8a7a6;
	}

	.yui-share-box {
		position: relative;
		margin: 0 auto;
	}

	.yui-share-blcok {
		margin: 0 auto;
	}

	.yui-share-block {
		position: absolute;
		left: 14%;
		bottom: 12%;
		z-index: 10000;
	}

	.inviteCodeBox {
		background: #fff;
		display: flex;
		justify-content: space-between;
		height: 220rpx;
		width: 100%;
		position: absolute;
		bottom: 0rpx;
		z-index: 1000;
		border-radius: 20rpx;
	}

	.inviteCode-nick {
		display: block;
		text-align: left;

		color: #a2a2a2;
	}

	.tui-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
	}

	.inviteCode-desc {
		margin-top: 10rpx;
		text-align: left;
		display: block;
	}

	.inviteCode-img {
		margin: 10rpx;
	}

	.yui-share {
		position: absolute;

		bottom: 40rpx;
		width: 100%;
	}

	.inviteCodeImgs {
		width: 170rpx;
		margin: 26rpx;

	}

	.share-member {
		display: flex;
		background: #fff;
		justify-content: space-between;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 24rpx;
		padding: 0rpx 20rpx 0rpx 20rpx;
	}

	.share_box {
		text-align: center;
		margin: 20rpx 0;
		justify-content: space-between;
		font-size: 22rpx;
		line-height: 34rpx;
		color: #353535;
		display: flex;
	}

	.share_box_span {
		display: block;
		width: 33%;
	}

	.share_box_text {
		display: block;
		text-align: center;
	}

	.share_icon {
		width: 60rpx;
	}

	.share_footer {
		width: 100%;
		position: fixed;
		bottom: 0rpx;
		height: 140rpx;
		z-index: 100000;
		background: #fff;

	}

	.inviteCodeImg-box-face-img {
		width: 100rpx;
		height: 100rpx;
		// background:#b8b8b8;
		border-radius: 50%;
		display: block;
	}

	.invteCode-nick-name {
		display: flex;
		justify-content: left;
		text-align: left;
		margin-bottom: 10rpx;
	}

	.inviteCodeImg-box-face-title {
		font-size: 24rpx;

		margin-left: 20rpx;
	}

	.inviteCodeImg-box-code-img {
		border-radius: 20rpx;
		width: 100%;
	}

	.inviteCodeImg-box-code {
		text-align: center;
		position: relative;
	}

	.canvas {
		// display: flex;
		// justify-content: center;
		// margin:60rpx auto;
		text-align: center;
	}

	.share-banner-box {}

	.inviteCode {
		min-height: 100%;
		position: relative;
		// background: linear-gradient(to bottom, #F9D981 , #F4BE5A);
		background-repeat: no-repeat;
		background-size: 100%;

	}



	.inviteCodeImg {
		border-radius: 20rpx;
		overflow: hidden;
		position: relative;
		width: 84%;
		margin: 30rpx auto 0 auto;
		text-align: center;
	}

	.inviteCode-name {
		word-break: break-all;
		overflow: hidden;
		align-items: center;
		max-width: 50%;
		height: 32rpx;
		text-overflow: ellipsis;
		// font-size: 28rpx;
		color: #666666;
	}

	.inviteCode-codes {
		font-size: 36rpx;
		color: #2f2f2f;
		font-weight: bold;
	}

	.inviteCodeImg-box {
		padding-top: 360rpx;
		padding-left: 260rpx;
		display: flex;

		align-items: center;
		justify-content: left;
	}
</style>